package com.ionehe.cola.common.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 集合操作工具类
 *
 * @author 2022/3/2 <a href="mailto:a@ionehe.com">skedison</a>
 */
public class CollUtil {
    private CollUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 集合根据属性去重
     *
     * @param keyExtractor 待去重的属性
     * @return {@link Predicate}<{@link T}>
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>(10);
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
